package com.wyq.group12.security;

import com.wyq.group12.entity.LoginUserEntity;
import com.wyq.group12.entity.PtUserEntity;
import com.wyq.group12.service.LoginService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName GdmtUserDetailsService
 * @Description: //TODO 用户认证授权
 * @Author wyq
 * @Date 2022/5/10 10:06
 */
@Service("userDetailsService")
public class GdmtUserDetailsService implements UserDetailsService {
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private LoginService loginService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        PtUserEntity ptUserEntity = loginService.queryUserInfoByUserName(username);
        if(ptUserEntity == null){
            throw new IllegalArgumentException(username + " user is not exit.");
        }

        List<GrantedAuthority> collection = new ArrayList<>();
        collection.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        collection.add(new SimpleGrantedAuthority("ROLE_USER_UPDATE"));
        collection.add(new SimpleGrantedAuthority("ROLE_TEST1"));
        collection.add(new SimpleGrantedAuthority("ROLE_USER_UPDATE"));
        // 参数分别是：用户名，密码，用户权限
        LoginUserEntity user = new LoginUserEntity(username, ptUserEntity.getPassword(), collection);
        user.setNiceName(ptUserEntity.getNiceName());
        user.setEmail(ptUserEntity.getEmail());
        user.setUserUuid(ptUserEntity.getUserUuid());
        user.setMobile(ptUserEntity.getMobile());

        return user;
    }
}

